package com.hjx.movie.core.player.controller;


import com.hjx.movie.common.utils.Result;
import com.hjx.movie.core.player.common.NonStaticResourceHttpRequestHandler;
import com.hjx.movie.core.player.service.PlayService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;


/**
 * <p>Title:</p>
 * <p>Description:</p>
 *
 * @author hjx
 * @date 2021/5/3 - 21:22
 */
@Slf4j
@RestController
@RequestMapping("/play")
public class PlayController {
    @Resource
    private NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;
    @Resource
    private PlayService playService;

    @GetMapping("/fileList")
    public Result getList(){
        return Result.success(playService.initFolderList());
    }

    @GetMapping("/deleteCache")
    public Result deleteCache(){
        playService.deleteCache();
        return Result.success("缓存清除成功");
    }


    @GetMapping("video")
    public void  videoPlayer(@RequestParam(name = "path") String path, HttpServletRequest request, HttpServletResponse response){
        try {
            if (StringUtils.isNotBlank(path)){
                log.info("接收到的入参文件地址为===>{}",path);
                String temp = path.replaceAll(" ","+");
                temp = new String(Base64.getDecoder().decode(temp.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8);
                log.info("============>{}",temp);
                Path filePath = Paths.get(temp);
                if (Files.exists(filePath)){
                    String mimeType = Files.probeContentType(filePath);
                    if(!StringUtils.isEmpty(mimeType)){
                        log.info(mimeType);
                        response.setContentType(mimeType);
                    }
                    request.setAttribute(NonStaticResourceHttpRequestHandler.ATTR_FILE,filePath);
                    nonStaticResourceHttpRequestHandler.handleRequest(request,response);
                }else {
                    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                    response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
                }
            }else{
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
            }
        } catch (Exception e) {
            log.info(e.getMessage());
//            e.printStackTrace();
        }
    }
}
